package com.qk.management.task;

import com.qk.management.mapper.UserMapper;
import com.qk.management.util.AliyunOSSOperators;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObjectSummary;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 16778
 * @date 2025/10/11 17:39
 * @description
 */
@Component
public class MyTask {

    @Autowired
    private AliyunOSSOperators ossOperators;

    @Autowired
    private UserMapper userMapper;

    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    private static final String BUCKET_NAME = "2025-qk-java-web-ai";
    private static final String REGION = "cn-beijing";

    @PostConstruct
    public void init() {
        // 服务启动时立即执行一次
        clean();
    }

    //每小时执行一次 (建议生产环境使用更长间隔)
    @Scheduled(cron = "0 0 * * * ?")
    public void clean(){
        System.out.println("开始执行OSS文件清理任务");

        try {
            // 1. 获取数据库中所有有效的图片路径
            List<String> validImages = getValidImagesFromDB();

            // 2. 获取OSS中所有文件
            List<String> ossObjects = listOSSObjects();

            // 3. 删除OSS中无效的文件
            deleteInvalidFiles(ossObjects, validImages);

            System.out.println("OSS文件清理任务执行完成");
        } catch (Exception e) {
            System.err.println("OSS文件清理任务执行失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 从数据库获取所有有效的图片路径
     */
    private List<String> getValidImagesFromDB() throws SQLException {
        List<String> images = new ArrayList<>();

        List<String> fullURL = userMapper.selectImages();

        for (String url : fullURL) {
            if (url != null && !url.isEmpty()) {
                String fileName = url.substring(url.lastIndexOf("/") + 1);
                images.add(fileName);
            }
        }
        return images;
    }

    /**
     * 列出OSS中所有对象
     */
    private List<String> listOSSObjects() {
        List<String> objects = new ArrayList<>();

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(ENDPOINT)
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(REGION)
                    .build();

            ObjectListing objectListing = ossClient.listObjects(BUCKET_NAME);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                objects.add(objectSummary.getKey());
            }
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return objects;
    }

    /**
     * 删除OSS中无效的文件
     */
    private void deleteInvalidFiles(List<String> ossObjects, List<String> validImages) {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(ENDPOINT)
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(REGION)
                    .build();

            for (String objectName : ossObjects) {
                // 如果OSS中的文件不在有效图片列表中，则删除
                if (!validImages.contains(objectName)) {
                    System.out.println("删除无效文件: " + objectName);
                    ossClient.deleteObject(BUCKET_NAME, objectName);
                }
            }
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
